package com.liukai.personalbills.activity;

/**
 * 增加账单界面
 */

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.liukai.personalbills.R;
import com.liukai.personalbills.adapter.AddRecyclerViewAdapter;
import com.liukai.personalbills.bean.Account;
import com.liukai.personalbills.bean.BillsBean;
import com.liukai.personalbills.bean.TypeBean;
import com.liukai.personalbills.bean.UserMessage;
import com.liukai.personalbills.retrofitInterface.AccountAPI;
import com.liukai.personalbills.util.ChangeColorUtil;
import com.liukai.personalbills.util.RetrofitManager;
import com.liukai.personalbills.util.TextUtil;
import com.liukai.personalbills.util.ToastUtil;

import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class AddActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView btnCancel;
    private TextView btnSave;
    private TextView btnIncome;
    private TextView btnExpend;
    private ArrayList<TextView> textViewArrayList;
    private Context context;
    private RecyclerView recyclerView;
    private ArrayList<TypeBean> typeBeanArrayList;
    private AddRecyclerViewAdapter adapter;
    private EditText etRemark;
    private EditText etMoney;
    private int imgIcon = R.mipmap.salary;
    private String type = "工资";
    private TypeBean typeBean;
    private ArrayList<TypeBean> typeBeansIncome;
    private ArrayList<TypeBean> typeBeansExpend;
    private TextView btnDate;
    private int mYear;
    private int mMonth;
    private int mDay;
    private boolean isUpdate = false; // 是否是修改数据
    private BillsBean lastBillsBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);

        context = AddActivity.this;

        initData();
        initView();
        initListener();

    }

    private void initView() {

        // 获取上一个界面传递的BillsBean
        Intent intent = getIntent();
        lastBillsBean = (BillsBean) intent.getSerializableExtra("billsBean");

        btnCancel = findViewById(R.id.btnCancel); // 取消按钮
        btnSave = findViewById(R.id.btnSave); // 保存按钮
        btnIncome = findViewById(R.id.btnIncome); // 消费类别收入
        btnExpend = findViewById(R.id.btnExpend); // 消费类别支出

        recyclerView = findViewById(R.id.recyclerView); // 列表
        // 适配器
        adapter = new AddRecyclerViewAdapter(context,typeBeanArrayList);
        GridLayoutManager layoutManager = new GridLayoutManager(context,5);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

        // 消费类别点击事件
        adapter.setOnItemClick((typeBean, position) -> {
            imgIcon = typeBean.getImgIcon();

            type = typeBean.getType();
            // 修改点击位置的消费类别样式
            updateTypeIcon(position);
//                ToastUtil.show(context,type);
        });
        // 消费类别List,存储消费类别（收入，支出）
        textViewArrayList = new ArrayList<>();
        textViewArrayList.add(btnIncome);
        textViewArrayList.add(btnExpend);

        etRemark = findViewById(R.id.etRemark);
        etMoney = findViewById(R.id.etMoney);
        btnDate = findViewById(R.id.btnDate);

        btnDate.setText(getDay(mYear,mMonth,mDay));

        // 上个界面传递的BillsBean不为空(说明传递过来的目的是为了修改)
        if(lastBillsBean != null){
            isUpdate = true; // 修改数据设为true
            etRemark.setText(lastBillsBean.getRemark());
            etMoney.setText(lastBillsBean.getMoney());
            btnDate.setText(lastBillsBean.getDate());
            // 判断上个界面传递的BillBean的类型是支出还是收入
            if(TextUtil.isIncome(lastBillsBean.getType())){
                ChangeColorUtil.changeTextViewColor(textViewArrayList,btnIncome,context);
                typeBeanArrayList.removeAll(typeBeanArrayList);
                typeBeanArrayList.addAll(typeBeansIncome);
                adapter.notifyDataSetChanged();
                updateTypeIcon(TextUtil.getIncomePosition(lastBillsBean.getType()));
            }else{
                ChangeColorUtil.changeTextViewColor(textViewArrayList,btnExpend,context);
                typeBeanArrayList.removeAll(typeBeanArrayList);
                typeBeanArrayList.addAll(typeBeansExpend);
                adapter.notifyDataSetChanged();
                updateTypeIcon(TextUtil.getExpendPosition(lastBillsBean.getType()));
            }

        }


    }

    /**
     * 初始化数据的类型
     */
    private void initData(){

        // 日期选择器
        Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);

        // 消费类别的图标
        typeBeanArrayList = new ArrayList<>();

        // 支出消费类别的列表
        typeBeansIncome = new ArrayList<>();
        for(int i = 0;i < TextUtil.INCOMES.length;i ++){
            typeBean = new TypeBean();
            typeBean.setType(TextUtil.INCOMES[i]);
            if(i == 0){
                // 默认点击选择的是第一个消费类别
                typeBean.setImgIcon(TextUtil.getClickIcon(TextUtil.INCOMES[i]));
            }else{
                // 设置支出消费类别的图标
                typeBean.setImgIcon(TextUtil.getNormalIcon(TextUtil.INCOMES[i]));
            }
            typeBeansIncome.add(typeBean);
        }


        // 收入消费类别的列表
        typeBeansExpend = new ArrayList<>();

        for(int i = 0;i < TextUtil.EXPENDS.length;i ++){
            typeBean = new TypeBean();
            typeBean.setType(TextUtil.EXPENDS[i]);
            if(i == 0){
                // 默认点击选择的是第一个消费类别
                typeBean.setImgIcon(TextUtil.getClickIcon(TextUtil.EXPENDS[i]));
            }else{
                // 设置收入消费类别的图标
                typeBean.setImgIcon(TextUtil.getNormalIcon(TextUtil.EXPENDS[i]));
            }
            typeBeansExpend.add(typeBean);
        }

        typeBeanArrayList.addAll(typeBeansExpend);


    }

    private void initListener(){

        btnCancel.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        btnIncome.setOnClickListener(this);
        btnExpend.setOnClickListener(this);
        btnDate.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        int id = view.getId();
        switch (id){
            case R.id.btnCancel :
                finish();
                break;

            case R.id.btnSave :
                saveData();
                break;

            case R.id.btnIncome :
                ChangeColorUtil.changeTextViewColor(textViewArrayList,btnIncome,context);
                typeBeanArrayList.removeAll(typeBeanArrayList);
                typeBeanArrayList.addAll(typeBeansIncome);
                adapter.notifyDataSetChanged();
                break;

            case R.id.btnExpend :
                ChangeColorUtil.changeTextViewColor(textViewArrayList,btnExpend,context);
                typeBeanArrayList.removeAll(typeBeanArrayList);
                typeBeanArrayList.addAll(typeBeansExpend);
                adapter.notifyDataSetChanged();
                break;

            case R.id.btnDate :
                new DatePickerDialog(context, onDateSetListener, mYear, mMonth, mDay).show();
                break;

        }

    }

    /**
     * 保存数据
     */
    private void saveData(){

        String remark = etRemark.getText().toString();
        String money = etMoney.getText().toString();
//        String remark = "111";
//        String money = "10000";
        String date = btnDate.getText().toString();

        if(money.equals("")){
            ToastUtil.show(context,"请输入金额!");
        }else{
            BillsBean billsBean = new BillsBean();
            billsBean.setRemark(remark);
            billsBean.setType(type);
            billsBean.setMoney(money);
            billsBean.setImgIcon(imgIcon);
            billsBean.setDate(date);
            if(TextUtil.isIncome(type)){
                billsBean.setTextColor(R.color.colorPrimaryDark);// 设置金额颜色
            }else{
                billsBean.setTextColor(R.color.colorAccent);// 设置金额颜色
            }
            if(isUpdate){
                updateToServer(billsBean);
            }else{
                if(saveToServer(billsBean)){

                }else{
                    ToastUtil.show(context,"系统故障，请稍后再试");
                    return;
                }
            }

    //        billsBeans.add(billsBean);
    //        billsTitleBean.setBillsBeanArrayList(billsBeans);

//           ToastUtil.show(context,"保存成功");


        }

    }

    /**
     * 时间选择对话框
     */
    private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;


            btnDate.setText(getDay(mYear,mMonth,mDay));
        }
    };

    /**
     * 获取时间
     * @param mYear
     * @param mMonth
     * @param mDay
     * @return
     */
    private String getDay(int mYear,int mMonth,int mDay){
        String days;
        if (mMonth + 1 < 10) {
            if (mDay < 10) {
                days = new StringBuffer().append(mYear).append("-").append("0").
                        append(mMonth + 1).append("-").append("0").append(mDay).append("").toString();
            } else {
                days = new StringBuffer().append(mYear).append("-").append("0").
                        append(mMonth + 1).append("-").append(mDay).append("").toString();
            }

        } else {
            if (mDay < 10) {
                days = new StringBuffer().append(mYear).append("-").
                        append(mMonth + 1).append("-").append("0").append(mDay).append("").toString();
            } else {
                days = new StringBuffer().append(mYear).append("-").
                        append(mMonth + 1).append("-").append(mDay).append("").toString();
            }

        }
        return days;
    }

    /**
     * 获取当前系统时间
     * @return
     */
    private String getTime(){
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式
        String time = df.format(new Date());// new Date()为获取当前系统时间
        return time;
    }

    /**
     * 刷新消费类别图标样式
     * @param position
     */
    private void updateTypeIcon(int position){

        for (int i = 0;i < typeBeanArrayList.size();i ++) {
            // 获取该位置的消费类别
            TypeBean typeBean = typeBeanArrayList.get(i);
            // 修改该位置的消费类别图标样式
            typeBean.setImgIcon(TextUtil.getNormalIcon(typeBean.getType()));
        }
        adapter.setAllTypeIcon(typeBeanArrayList);
        // 获取点击位置的消费类别，并根据消费类别设置对应的点击后的图标样式，传入adapter中
        adapter.setTypeIcon(new TypeBean(TextUtil.getClickIcon(typeBeanArrayList.get(position).getType())),position);
    }

    /**
     * 将账单存储到服务器
     * @param billsBean
     */
    private boolean saveToServer(BillsBean billsBean){

//        final boolean[] result = {false};
//        AccountMessage accountMessage = new AccountMessage();
        Account account = new Account();
        String date = billsBean.getDate();
        String money = billsBean.getMoney();
        String remark = billsBean.getRemark();
        String type = billsBean.getType();
        account.setDate(date);
        account.setMoney(money);
        account.setRemark(remark);
        account.setType(type);
        account.setTime(getTime());

        ToastUtil.log(context,"account",account.toString());
        // 使用Retrofit框架
        AccountAPI accountAPI = RetrofitManager.getAccountAPI();
        Gson gson = new Gson();
        String accountJson = gson.toJson(account);
        Call<UserMessage> addAccountTask = accountAPI.addAccount(accountJson,TextUtil.username);
        addAccountTask.enqueue(new Callback<UserMessage>() {
            @Override
            public void onResponse(Call<UserMessage> call, Response<UserMessage> response) {
                int code = response.code();
                if(code == HttpURLConnection.HTTP_OK){
                    Intent intent = new Intent();
                    intent.putExtra("billsBean",billsBean);
                    setResult(TextUtil.RES_MAINACTIVITY,intent);
                    ToastUtil.show(context,"保存成功");
                    finish();
                }else{
//                    result[0] = false;
                }
                ToastUtil.log(context,"code",code+"");
                ToastUtil.show(context,"code==========>" + code + "");
//                ToastUtil.log(context,"onResponse",response.body().toString());
            }

            @Override
            public void onFailure(Call<UserMessage> call, Throwable t) {
                ToastUtil.log(context,"onFailure",t.toString());
//                result[0] = false;
            }
        });
        return true;
    }

    /**
     * 修改服务器中的数据
     * @param billsBean
     */
    private void updateToServer(BillsBean billsBean) {

        final boolean[] result = {false};
//        AccountMessage accountMessage = new AccountMessage();
        Account account = new Account();
        String date = billsBean.getDate();
        String money = billsBean.getMoney();
        String remark = billsBean.getRemark();
        String type = billsBean.getType();
        account.setDate(date);
        account.setMoney(money);
        account.setRemark(remark);
        account.setType(type);
        account.setTime(getTime());
        account.setTimeId(lastBillsBean.getTimeId());

        ToastUtil.log(context,"account",account.toString());
        // 使用Retrofit框架
        AccountAPI accountAPI = RetrofitManager.getAccountAPI();
        Gson gson = new Gson();
        String accountJson = gson.toJson(account);
        Call<UserMessage> updateAccountTask = accountAPI.updateAccount(accountJson,TextUtil.username);
        updateAccountTask.enqueue(new Callback<UserMessage>() {
            @Override
            public void onResponse(Call<UserMessage> call, Response<UserMessage> response) {
                int code = response.code();
                if(code == HttpURLConnection.HTTP_OK){
                    Intent intent = new Intent();
                    intent.putExtra("billsBean",billsBean);
                    setResult(TextUtil.RES_MAINACTIVITY,intent);
                    ToastUtil.show(context,"修改成功");
                    finish();
                }else{
//                    result[0] = false;
                }
                ToastUtil.log(context,"code",code+"");
                ToastUtil.show(context,"code==========>" + code + "");
//                ToastUtil.log(context,"onResponse",response.body().toString());
            }

            @Override
            public void onFailure(Call<UserMessage> call, Throwable t) {
                ToastUtil.log(context,"onFailure",t.toString());
//                result[0] = false;
            }
        });
//        return true;

    }


}
